# !/usr/bin/env python
# -*- encoding: utf-8 -*-

from .data_prepare import *
import jieba as jb
import pandas as pd
import numpy as np
from threading import Lock, Thread
import traceback

emotion_list = ['positive', 'negative',
                'happy', 'like', 'surprised', 'angry', 'sad', 'fear', 'hate',
                'joyful', 'relieved', 'respect', 'praise', 'believe', 'like', 'hopeful', 'surprised',
                'angry', 'sad', 'disappointed', 'remorse', 'miss', 'fear', 'ashamed', 'flustered',
                'disgusted', 'annoyed', 'reproach', 'jealousy', 'suspect']


print('读取字典..')
emotion_df = pd.read_excel('dataset/emotion_matrix.xlsx')
matrix = emotion_df.iloc[:, np.arange(1, emotion_df.shape[1])].to_numpy()
words = emotion_df.iloc[:, [0]].to_numpy()


def func(start=0, end=2000):
    result = np.zeros((end-start, 30), dtype=np.int8)
    comments = data[:, [1]]
    for i in range(start, end):
        try:
            if type(comments[i][0]) == float:
                continue
            if len(comments[i][0]) == 0:
                continue
            voc = jb.lcut(comments[i][0])
            ins, temp = np.where(voc == words)
            for index in ins:
                result[i-start] += matrix[index]
        except Exception as e:
            info = traceback.format_exc()
            print('处理第', i, '条数据出错', comments[i], ' \ninfo:\n', info)
    return result


def multi_threads_solute(step=5000):
    li = np.concatenate([np.arange(start=0, step=5000, stop=len(data)), [len(data)]])
    threads = []
    for i in range(1, len(li)):
        start, end = li[i-1], li[i]
        t = myThread(fileName='matrix{}'.format(i), start=start, end=end)
        threads.append(t)
        t.start()
    # for t in threads:
    #     t.join()



class myThread(Thread):
    def __init__(self, fileName, start, end):
        super(myThread, self).__init__()
        self.fileName = fileName
        self.left = start
        self.right = end

    def run(self):
        print(self.name, ' 线程启动')
        result = func(start=self.left, end=self.right)
        out = pd.DataFrame(result, columns=emotion_list)
        out.insert(0, 'singId', value=data[self.left: self.right, [0]])
        out.to_csv('result/' + self.fileName + '.csv', index=None)
        print(self.name, ' 线程结束')


if __name__ == '__main__':
    print('===================start====================')
    multi_threads_solute(5000)
    # result = func()
    # out = pd.DataFrame(result, columns=emotion_list)
    # out.insert(0, 'singId', value=data[: 2000, [0]])
    # print(out.info())
    # print(out.head())

